import 'package:aqua_plunge/constants/colors.dart';
import 'package:aqua_plunge/dao/broadcaster_dao.dart';
import 'package:aqua_plunge/widget/app_bar.dart';
import 'package:aqua_plunge/widget/custom_avatar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_util_code/toast_utils.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:permission_handler/permission_handler.dart';

import '../constants/constants.dart';
import '../controller/UserController.dart';
import '../cover/LogPvManager.dart';

class EditPage extends StatefulWidget {
  const EditPage({super.key});

  @override
  State<EditPage> createState() => _EditPageState();
}

class _EditPageState extends State<EditPage> {
  TextEditingController? _nameController;
  TextEditingController? _countryController;

  final UserController _userController = Get.find<UserController>();

  final ImagePicker _picker = ImagePicker();
  String? selectPath;
  DateTime? _selectedDate;
  final DateTime _minDate = DateTime.now();
  final DateFormat _dateFormat = DateFormat('yyyy-MM-dd');

  get _contentView => Container(
      padding: const EdgeInsets.fromLTRB(24, 28, 24, 28),
      decoration: const BoxDecoration(
          image: DecorationImage(
              image: AssetImage('images/img_primary_bg.png'),
              fit: BoxFit.cover)),
      child: ListView(
        children: [
          Container(
            width: double.infinity,
            alignment: Alignment.center,
            padding: const EdgeInsets.only(top: 32, bottom: 42),
            child: Stack(
              children: [
                ClipOval(
                  child: selectPath == null
                      ? CustomAvatar(
                          width: 98,
                          height: 98,
                          netPath: _userController.userInformation.avatarUrl??_userController.userInformation.avatar??'',
                        )
                      : Image.asset(
                          selectPath!,
                          width: 98,
                          height: 98,
                          fit: BoxFit.cover,
                        ),
                ),
                Positioned(
                    right: 0,
                    bottom: 0,
                    child: GestureDetector(
                        onTap: () async {
                            _addPicture();
                        },
                        child: Image.asset(
                          'images/icon_profile.png',
                          width: 36,
                          height: 36,
                        )))
              ],
            ),
          ),
          _buildItem(Row(
            children: [
              const Text('Nick Name',
                  style: TextStyle(color: AppColors.grayColor, fontSize: 14)),
              Expanded(child: Container()),
              Expanded(
                  child: TextField(
                controller: _nameController,
                textAlign: TextAlign.right,
                style: const TextStyle(color: Colors.white, fontSize: 14),
                decoration: InputDecoration(
                    border: InputBorder.none,
                    hintText: _userController.userInformation.nickname,
                    hintStyle:
                        const TextStyle(color: Colors.white, fontSize: 14)),
              ))
            ],
          )),
          _buildItem(Row(
            children: [
              const Text('Date of Birth',
                  style: TextStyle(color: AppColors.grayColor, fontSize: 14)),
              Expanded(child: Container()),
              Expanded(
                child: InkWell(
                  onTap: () {
                    _selectDate(context);
                  },
                  child: Text(
                    _formatDate(_selectedDate ?? DateTime.now()),
                    textAlign: TextAlign.right,
                    style: const TextStyle(color: Colors.white, fontSize: 14),
                  ),
                ),
              )
            ],
          )),
          _buildItem(Row(
            children: [
              const Text('Country',
                  style: TextStyle(color: AppColors.grayColor, fontSize: 14)),
              Expanded(child: Container()),
              Expanded(
                  child: TextField(
                controller: _countryController,
                textAlign: TextAlign.right,
                style: const TextStyle(color: Colors.white, fontSize: 14),
                decoration: InputDecoration(
                    border: InputBorder.none,
                    hintText: _userController.userInformation.country ?? "",
                    hintStyle:
                        const TextStyle(color: Colors.white, fontSize: 14)),
              ))
            ],
          )),
          const SizedBox(
            height: 168,
          ),
          InkWell(
            child: Container(
                height: 48,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(20),
                    color: Colors.white),
                child: Center(
                  child: GestureDetector(
                    child: const Text('Submit',
                        style: TextStyle(
                            color: AppColors.primaryColor, fontSize: 20)),
                  ),
                )),
            onTap: () {
              _saveUserInfo();
            },
          )
        ],
      ));

  _saveUserInfo() async {
    await BroadCasterDao.saveUserInfo(
        _formatDate(_selectedDate ?? DateTime.now()),
        _countryController!.text.isEmpty
            ? _userController.userInformation.country!
            : _countryController!.text.toString(),
        _nameController!.text.isEmpty
            ? _userController.userInformation.nickname!
            : _nameController!.text.toString(), () {
      _userController.updateInfo();
      Get.back();
    });
  }

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController();
    _countryController = TextEditingController();
    _selectedDate = DateTime.parse(_userController.userInformation.birthday);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: appBar("Edit Profile"),
        body: Obx(() {
          return _contentView;
        }));
  }

  Widget _buildItem(Widget childview) {
    return Container(
      height: 70,
      margin: const EdgeInsets.only(top: 20),
      width: double.infinity,
      padding: const EdgeInsets.only(left: 20, right: 20),
      decoration: BoxDecoration(
        image: const DecorationImage(
            image: AssetImage('images/list_item_bg.png'), fit: BoxFit.cover),
        borderRadius: BorderRadius.circular(12),
      ),
      child: childview,
    );
  }

  Future<void> _addPicture() async {
    final status = await Permission.camera.request();
    if (status.isGranted) {
      final pickedFile = await _picker.pickImage(source: ImageSource.camera);
      LogPvManager.stat(page: Constants.pagePurchase);
      setState(() {
        if (pickedFile != null) {
          selectPath = pickedFile.path;
          BroadCasterDao.getOssPolicy().then((policy) =>
              BroadCasterDao.uploadAvatar(policy!, pickedFile)
                  .then((avatarPath) {
                BroadCasterDao.updateAvatar(avatarPath, () {
                  //todo
                });
              }));
        }
      });
    }
  }

  Future<void> _selectDate(BuildContext context) async {
    final DateTime? newSelectedDate = await showDatePicker(
      context: context,
      initialDate: _selectedDate ?? _minDate,
      firstDate: DateTime(1900),
      lastDate: _minDate,
    );
    if (newSelectedDate != null && newSelectedDate != _selectedDate) {
      final age = _calculateAge(newSelectedDate);
      if (age >= 18) {
        setState(() {
          _selectedDate = newSelectedDate;
        });
      } else {
        ToastUtils.showCenter("You must be at least 18 years old.");
      }
    }
  }

  int _calculateAge(DateTime birthDate) {
    final now = DateTime.now();
    final age = now.year - birthDate.year;
    if (now.month < birthDate.month ||
        (now.month == birthDate.month && now.day < birthDate.day)) {
      return age - 1;
    } else {
      return age;
    }
  }

  String _formatDate(DateTime date) {
    return _dateFormat.format(date);
  }

  String getOssKey(String dir, String fileName) {
    if (dir.isEmpty || fileName.isEmpty) return "";
    var suffixIndex = fileName.lastIndexOf(".");
    var fileType = (suffixIndex > 0) ? fileName.substring(suffixIndex) : "";
    var osskey = "$dir${DateTime.now().millisecond}$fileType";
    return osskey;
  }
}
